/**
 * @Author: easten
 * @Created: 2024-04-15 23:48:14
 * @Description:
 *
 */
import { ApiStation } from "_common/api/iot/ApiStation";
import { DrawerProps } from "_common/DataType";
import { IotStation } from "_common/entity";
import { AxiosInstance } from "axios";
import React, { useState, useEffect, useMemo, useRef } from "react";
import {
  Button,
  Drawer,
  Form,
  FormInstanceFunctions,
  Input,
  Select,
} from "tdesign-react";
import FormItem from "tdesign-react/es/form/FormItem";
export type StationDrawerProps = DrawerProps & {
  axios: AxiosInstance;
};
const StationDrawer: React.FC<StationDrawerProps> = (
  props: StationDrawerProps
) => {
  const { open, axios, edit, onSuccess, value } = props;
  const formRef = useRef<FormInstanceFunctions>();

  // 列表状态
  const apiStation = new ApiStation(axios);

  useEffect(() => {
    return () => {
      formRef.current?.reset();
    };
  }, []);

  useEffect(() => {
    if (value && edit) {
      formRef.current?.setFieldsValue(value);
    }
  }, [edit, value]);

  const handleClose = () => {
    onSuccess?.(false);
    formRef.current?.reset();
  };

  // 新增站点
  const createStation = async (data: IotStation) => {
    const response = await apiStation.create(data);
    if (response && response.code == 200) {
      handleClose();
    }
  };
  // 更新站点
  const updateStation = async (data: IotStation) => {
    const response = await apiStation.update({
      ...data,
      id: value?.id,
    });
    if (response && response.code == 200) {
      handleClose();
    }
  };

  return (
    <Drawer
      header={`${edit ? "编辑" : "添加"}站点`}
      footer={false}
      visible={open}
      sizeDraggable
      size="medium"
      onClose={handleClose}
    >
      <Form
        ref={formRef}
        labelWidth={100}
        onSubmit={async (data) => {
          // 是否校验通过
          if ((await formRef.current?.validateOnly()) == true) {
            edit
              ? updateStation(data.fields as IotStation)
              : createStation(data.fields as IotStation);
          }
        }}
      >
        <FormItem label="站点名称" rules={[{ required: true }]} name="name">
          <Input />
        </FormItem>
        <FormItem label="站点编码" rules={[{ required: true }]} name="code">
          <Input />
        </FormItem>
        <FormItem
          label="站点地址"
          rules={[{ required: false }]}
          name="location"
        >
          <Input />
        </FormItem>
        <FormItem label="描述" rules={[{ required: false }]} name="desc">
          <Input />
        </FormItem>
        <FormItem className="float-right">
          <Button type="submit" theme="primary">
            提交
          </Button>
          <Button type="reset" theme="success" style={{ marginLeft: 12 }}>
            重置
          </Button>
        </FormItem>
      </Form>
    </Drawer>
  );
};
export default StationDrawer;
